using System.Collections.Generic;
using UnityEngine;
using System;
using System.Threading.Tasks;
using UnityEngine.UI;


public class RoundRank : MonoBehaviour
{

    [SerializeField] private ScrollRect scrollRect;       // 滑动组件
    [SerializeField] private Transform rankListContent;   // 排行榜列表容器
    [SerializeField] private GameObject rankItemPrefab;   // 排行榜项预制体

    [Header("Top 3 UI References")]
    [SerializeField] private Transform[] top3Positions;    // 前三名位置
    [SerializeField] private Image[] top3Avatars;         // 前三名头像
    [SerializeField] private Text[] top3Names;            // 前三名昵称

    // 排行榜数据结构
    [Serializable]
    public class GameUser
    {
        public int id;                          // 用户ID
        public string name;                     // 用户名称
        public string avatar_url;               // 头像URL
    }

    [Serializable]
    public class RankData
    {
        public int id;                          // 记录ID
        public int game_user_id;                // 玩法用户ID
        public int group_id;                    // 组ID
        public int round_total_nums;            // 回合总次数
        public int round_success_nums;          // 回合成功次数
        public int round_score;                 // 回合得分
        public int round_total_score;           // 回合总分
        public int start_level;                 // 开始等级
        public int start_ranking;               // 开始排名
        public int start_score;                 // 开始分数
        public int start_success_nums;          // 开始成功次数
        public int start_total_nums;            // 开始总次数
        public int end_ranking;                 // 结束排名
        public int end_level;                   // 结束等级
        public int end_score;                   // 结束分数
        public int end_success_nums;            // 结束成功次数
        public int end_total_nums;              // 结束总次数
        public GameUser game_user;              // 玩法用户信息
    }

    [Serializable]
    public class RankResponse
    {
        public int status;                      // 状态码
        public List<RankData> data;             // 排行榜数据
    }

    private const string BASE_URL = "https://api.question.game.xmnk.cn/";
    private const int DEFAULT_PAGE_SIZE = 15;
    private int currentPage = 1;
    private bool isLoading = false;
    private float scrollThreshold = 0.8f; // 滑动阈值，超过这个值就加载下一页
    private bool hasMoreData = true; // 是否还有更多数据

    private static readonly string[] LevelNames = { "幼儿园", "小学生", "初中生", "高中生" ,"大学生","博士生"};

    private void Start()
    {
        InitializeUI();
        GetDefaultRank();
    }

    private void InitializeUI()
    {
        // 添加滑动监听
        scrollRect.onValueChanged.AddListener(OnScrollValueChanged);
    }


    private void OnScrollValueChanged(Vector2 value)
    {
        if (!isLoading && hasMoreData && value.y <= 0.05f)
        {
            LoadNextPage();
        }
    }

    private void LoadRankList()
    {
        isLoading = true;
        GetRankList(currentPage, DEFAULT_PAGE_SIZE, OnRankListReceived);
    }

    private void LoadNextPage()
    {
        if (!isLoading && hasMoreData)
        {
            currentPage++;
            LoadRankList();
        }
    }

    private void ClearRankList()
    {
        // 隐藏前三名
        if (top3Positions != null)
        {
            foreach (var pos in top3Positions)
            {
                if (pos != null)
                    pos.gameObject.SetActive(false);
            }
        }

        // 清除列表
        foreach (Transform child in rankListContent)
        {
            Destroy(child.gameObject);
        }
    }

    private void OnRankListReceived(RankResponse response)
    {
        isLoading = false;
        if (response != null && response.status == 0 && response.data != null)
        {
            Debug.Log("收到数据条数: " + response.data.Count);
            UpdateRankListUI(response.data);

            // 判断是否还有更多数据
            if (response.data.Count < DEFAULT_PAGE_SIZE)
            {
                hasMoreData = false; // 没有更多数据了
            }
            else
            {
                hasMoreData = true; // 还有下一页
            }
        }
        else
        {
            Debug.LogError("获取排行榜数据失败, response is null: " + (response == null));
            // hasMoreData = false; // 请求失败也不再请求
        }
    }

    private void UpdateRankListUI(List<RankData> rankDataList)
    {
        // 只有第一页才处理前三名
        if (currentPage == 1)
        {
            // 处理前三名
            for (int i = 0; i < Mathf.Min(3, rankDataList.Count); i++)
            {
                var rankData = rankDataList[i];
                if (top3Positions != null && top3Positions.Length > i)
                {
                    top3Positions[i].gameObject.SetActive(true);
                    if (top3Avatars != null && top3Avatars.Length > i)
                        ImageLoader.Instance.LoadImageFromUrl(top3Avatars[i], rankData.game_user.avatar_url);
                    if (top3Names != null && top3Names.Length > i)
                        top3Names[i].text = rankData.game_user.name;
                }
            }
        }

        // 创建列表项（重复显示前三名详细信息）
        for (int i = 0; i < rankDataList.Count; i++)
        {
            GameObject rankItem = Instantiate(rankItemPrefab, rankListContent);
            UpdateRankItemUI(rankItem, rankDataList[i]);
        }
    }

    private void UpdateRankItemUI(GameObject rankItem, RankData rankData)
    {
        // 排名
        var rankText = rankItem.transform.Find("rank/Text").GetComponent<UnityEngine.UI.Text>();
        rankText.text = (rankListContent.childCount).ToString(); // 加3是因为前三名单独显示

        //世界排名
        var worldRankText = rankItem.transform.Find("rank/WorldText").GetComponent<UnityEngine.UI.Text>();
        if (rankData.end_ranking == 0){
            worldRankText.text = "--";
        }else{
            worldRankText.text = rankData.end_ranking.ToString();
        }

        // 头像
        var avatarImage = rankItem.transform.Find("user/Avatar").GetComponent<UnityEngine.UI.Image>();
        ImageLoader.Instance.LoadImageFromUrl(avatarImage, rankData.game_user.avatar_url);

        // 昵称
        var nickText = rankItem.transform.Find("user/Nick").GetComponent<UnityEngine.UI.Text>();
        nickText.text = rankData.game_user.name;

        // 段位（映射）
        var duanweiText = rankItem.transform.Find("Duanwei/Text").GetComponent<UnityEngine.UI.Text>();
        if (rankData.end_level >= 0 && rankData.end_level < LevelNames.Length)
            duanweiText.text = LevelNames[rankData.end_level];
        else
            duanweiText.text = "未知";

        // 答题
        var datiText = rankItem.transform.Find("Dati/Text").GetComponent<UnityEngine.UI.Text>();
        datiText.text = $"{rankData.round_total_nums}";

        //答题正确率
        var duigongText = rankItem.transform.Find("ZhengQueLv/Text").GetComponent<UnityEngine.UI.Text>();
        int percentage = rankData.round_total_nums > 0 ? (rankData.round_success_nums * 100 / rankData.round_total_nums) : 0;
        duigongText.text = $"{percentage}%";

        // 积分
        var jifenText = rankItem.transform.Find("Jifen/Text").GetComponent<UnityEngine.UI.Text>();
        jifenText.text = rankData.round_total_score.ToString();
    }

    // 获取排行榜数据
    public async void GetRankList(int page = 1, int pageSize = DEFAULT_PAGE_SIZE, Action<RankResponse> callback = null)
    {
        
        string endpoint = "round/timeDataPaginate";
        await FetchRankData(endpoint, page, pageSize, callback);
    }

   

    // 获取默认排行榜（积分排行）
    public void GetDefaultRank()
    {
        GetRankList(currentPage, DEFAULT_PAGE_SIZE, OnRankListReceived);
    }

    // 发送网络请求获取排行榜数据
    private async Task FetchRankData(string endpoint, int page, int pageSize, Action<RankResponse> callback)
    {
        RankResponse rankResponse = null;
        try
        {
            var response = await HttpClientService.Instance
                .Get(endpoint)
                .AddQueryParam("round_id", GlobalData.RoundId)//GlobalData.RoundId
                .AddQueryParam("page", page.ToString())
                .AddQueryParam("pre_page", pageSize.ToString())
                .SendAsync();

            if (response.IsSuccess)
            {
                try
                {
                    if (string.IsNullOrEmpty(response.Content))
                    {
                        Debug.LogError("FetchRankData: response.Content is null or empty!");
                    }
                    else
                    {
                        rankResponse = JsonUtility.FromJson<RankResponse>(response.Content);
                        Debug.Log($"FetchRankData: 反序列化成功, status={rankResponse?.status}, data count={rankResponse?.data?.Count ?? -1}");
                    }
                }
                catch (Exception ex)
                {
                    Debug.LogError($"FetchRankData: 反序列化异常: {ex.Message}");
                    Debug.LogError($"FetchRankData: 原始内容: {response.Content}");
                }
            }
            else
            {
                Debug.LogError($"FetchRankData: 网络请求失败: {response.ErrorMessage}");
            }
        }
        catch (Exception ex)
        {
            Debug.LogError($"FetchRankData: 网络异常: {ex.Message}");
        }

        // 只在最后统一回调
        callback?.Invoke(rankResponse);
    }

}

